<script setup lang="tsx">

import { SyslogloginApi } from '@/api-services/apis/sysloglogin-api';
import OperateModal from './modules/operate-modal.vue';
import { ApiSysLogLoginQuery, ApiSysLogLoginOut } from '@/api-services';
import { getAPI, feature } from '@/axios-utils';
import { useTableScroll, fetchTableQuery, useNetoTable, useTableOperate } from '@/hooks/common/neto-table';
import { $t } from '@/locales';
import { queryDone } from '@/utils/api';
import { ref } from 'vue';
import Search from './modules/search.vue';
import { ElButton, ElPopconfirm, ElTag } from 'element-plus';
defineOptions({ name: 'LoginLog' });

const { tableWrapperRef, scrollConfig } = useTableScroll();
// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const apiFunc = (params: ApiSysLogLoginQuery) =>
  fetchTableQuery<ApiSysLogLoginQuery, ApiSysLogLoginOut>(params, (internalParams: ApiSysLogLoginQuery) =>
    getAPI(SyslogloginApi).getList(internalParams)
  );

const loadingStates = ref<Record<string, boolean>>({});

const {
  columns,
  columnChecks,
  data,
  tableSize,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useNetoTable({
  apiFn: apiFunc,
  size: 'small',
  // apiFn:fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList),
  // apiFn: fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList.bind(getAPI(ApiuserserviceApi))),
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    keyWords: '',
    startDate: undefined,
    endDate: undefined,
    type: undefined,
    status: undefined
  },
  columns: () => [
    { type: 'selection', width: 48 },
    {
      prop: 'id',
      //dataIndex: 'id',
      label: 'id',
      minWidth: 130
    },
    {
      //创建时间
      prop: 'creationTime',
      //dataIndex: 'creationTime',
      label: $t('common.creationTime'),
      align: 'center',
      minWidth: 150
    },
    {
      //账号
      prop: 'account',
      //dataIndex: 'account',
      label: $t('page.sysLoginLog.account'),
      align: 'center',
      minWidth: 170
    },

    {
      //IP
      prop: 'ip',
      //dataIndex: 'ip',
      label: 'IP',
      align: 'center',
      minWidth: 110
    },

    {
      //浏览器
      prop: 'browser',
      //dataIndex: 'browser',
      label: $t('page.sysLoginLog.browser'),
      align: 'center',
      minWidth: 170
    },

    {
      //操作系统
      prop: 'os',
      //dataIndex: 'os',
      label: $t('page.sysLoginLog.os'),
      align: 'center',
      minWidth: 170
    },
    {
      //登陆用户类型
      prop: 'type',
      //dataIndex: 'type',
      label: $t('page.sysLoginLog.type'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        switch (record.type) {
          case 0:
            return <ElTag type="success">{$t('page.sysLoginLog.typeEnum.admin')}</ElTag>;
          default: return '';
        }
      }
    },
    {
      //登陆状态
      prop: 'status',
      //dataIndex: 'status',
      label: $t('page.sysLoginLog.status'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        switch (record.status) {
          case 1:
            return <ElTag type="success">{$t('common.success')}</ElTag>;
          case 0:
            return <ElTag type="warning">{$t('common.failed')}</ElTag>;
          default: return '';
        }
      }
    },
    {
      //结果
      prop: 'result',
      //dataIndex: 'result',
      label: $t('page.sysLoginLog.result'),
      align: 'center',
      minWidth: 170
    },
    {
      //表ID
      prop: 'tableId',
      //dataIndex: 'tableId',
      label: $t('page.sysLoginLog.tableId'),
      align: 'center',
      hide: true,
      minWidth: 170
    },
    {
      //请求地址
      prop: 'requestUrl',
      //dataIndex: 'requestUrl',
      label: $t('page.sysLoginLog.requestUrl'),
      align: 'center',
      hide: true,
      minWidth: 170
    },
    {
      prop: 'index',
      label: $t('common.operate'),
      align: 'center',
      minWidth: 230,
      fixed: 'right',
      formatter: record => (
        <div class="flex-center gap-8px">
          <ElButton type="primary" plain size="small" onClick={() => edit(record.id!)}>
            {$t('common.edit')}
          </ElButton>
          <ElPopconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(record.id!)}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});

const {
  isVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  //rowSelection,
  onBatchDeleted,
  onDeleted
} = useTableOperate(data, getData);
const edit = (id: number) => {
  // console.log(id);
  handleEdit(id);
};
const handleDelete = async (id: number) => {

  // 提交请求
  const [err, res] = await feature(getAPI(SyslogloginApi).batchDelete(id.toString()));

  queryDone(err, async () => {
    if (res?.data.data) {
      onDeleted();
    } else {
      // 失败
      window.$message?.error($t('common.failed'));
    }
  });
};
const handleBatchDeleted = async () => {
  if (!checkedRowKeys.value) {
    return;
  }
  const ids = checkedRowKeys.value.join(',');

  // 提交请求
  const [err, res] = await feature(getAPI(SyslogloginApi).batchDelete(ids));

  queryDone(err, async () => {
    if (res?.data.data) {
      onBatchDeleted();
    } else {
      // 失败
      window.$message?.error($t('common.failed'));
    }
  });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <!-- 登录日志 -->
    <Search v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage"></Search>
    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.sysLoginLog.titleName') }}</p>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            v-model:size="tableSize" :show-table-size="true" :loading="loading" :show-add="false"
            @delete="handleBatchDeleted" @refresh="getData" />
        </div>
      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>
      <OperateModal v-model:visible="isVisible" :operate-type="operateType" :row-data="editingData"
        @submitted="getDataByPage" />
    </ElCard>
  </div>
</template>

<style scoped></style>
